package com.nicy.dream.biz;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @projectName:dream
 * @see:com.nicy.dream.biz
 * @author:NicyYe
 * @createTime:2021/3/3 17:48
 * @version:1.0
 */
@Slf4j
@CrossOrigin
@Api(tags = "RLock控制器")
@RestController
@RequestMapping("/rlock")
public class RLockController {

    @Autowired
    private RedissonClient redissonClient;

    @ApiOperation(value = "redisson分布式锁测试")
    @GetMapping("/redisson")
    public String testRedisson(String name){
        //获取分布式锁
        //RLock lock = redissonClient.getLock(name);

        RLock lock = redissonClient.getFairLock(name);
        //加锁（阻塞等待），默认过期时间是30秒
        lock.lock();

        //设置加锁时间
        //lock.lock(10, TimeUnit.SECONDS);
        boolean getLock = false;


        try {
            getLock = lock.tryLock(5,10,TimeUnit.SECONDS);
            //如果业务执行过长，redisson会自动续期
            Thread.sleep(9000);
            System.out.println("加锁成功,执行业务逻辑");
        }catch (InterruptedException e){
            log.info("获取分布式锁失败");
            e.printStackTrace();
        }finally {
           if(getLock) {
               //解锁，如果业务执行完成，就不会续期；即使没有手动释放解锁，在30秒过后，也会释放锁
               lock.unlock();
           }
        }

       return "Hello Redisson";
    }


}
